package org.example.service;

import lombok.extern.slf4j.Slf4j;
import reactor.util.retry.Retry;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.web.reactive.function.client.WebClient;

import java.time.Duration;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicInteger;

import javax.annotation.Resource;

/**
 * NetworkConnectivityService
 *
 * @author: wangchao
 * @Date: 2025/6/11 09:30
 * @since 7.0.0-RC2
 **/
@Slf4j
@Service
public class NetworkConnectivityService {
    private static final String DEFAULT_HEALTH_ENDPOINT = "/agent/health";
    private static final int DEFAULT_TIMEOUT_MS = 3000;
    private static final int DEFAULT_RETRY_ATTEMPTS = 3;
    @Value("${network.check.endpoint:#{null}}")
    private String healthEndpoint;

    @Value("${network.check.timeout:" + DEFAULT_TIMEOUT_MS + "}")
    private int timeoutMs;

    @Value("${network.check.retry.attempts:" + DEFAULT_RETRY_ATTEMPTS + "}")
    private int retryAttempts;

    @Value("${network.check.retry.delay:500}")
    private int retryDelayMs;
    @Resource
    private RetryService retryService;
    private final WebClient webClient;

    public NetworkConnectivityService(WebClient webClient) {
        this.webClient = webClient;
    }

    public ConnectivityResult checkConnectivityWithRetry(String baseUrl) {
        try {
            return retryService.executeWithRetry(() -> {
                String fullUrl = baseUrl + DEFAULT_HEALTH_ENDPOINT;

                HttpStatus status = webClient.head()
                    .uri(fullUrl)
                    .retrieve()
                    .toBodilessEntity()
                    .map(entity -> entity.getStatusCode())
                    .block();

                return new ConnectivityResult(true, status.value(), "Connected successfully");
            });
        } catch (RetryException e) {
            return new ConnectivityResult(false, 0, "Failed to connect after retries: " + e.getMessage());
        }
    }

    /**
     * 判断是否为可重试的异常
     */
    private boolean isRetryableException(Throwable e) {
        // 网络相关异常可以重试
        return e instanceof java.net.ConnectException || e instanceof java.net.SocketTimeoutException
            || e instanceof TimeoutException;
    }


}
